/*
 * @(#)SplashScreen.java    1.0
 *
 * Copyright 2009 GFE, All rights reserved.
 * Game For Education.
 */
package egfe;

import java.io.IOException;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.GameCanvas;

/**
 *
 * @author  Sajarwo Anggai
 * @author  Abdul Rizal Adompo
 * @version 1.0, 11 May 2009
 * @see	    MainMenu
 * @see	    GFEInfo
 */
public class SplashScreen extends GameCanvas implements Runnable {

    private int delayTime = 3;
    private Image img;
    private MainMenuAction next;
    private Display display;
    private boolean stop;
    public Graphics graphics;

    /** 
     * Constructor SplashScreen melewatkan parameter delayTime
     * @param delayTime setting dalam satuan detik(s)      
     */
    public SplashScreen(int delayTime) {
        super(true);
        if (delayTime > 0) {
            this.delayTime = delayTime;
        }
        setFullScreenMode(true);
        graphics = getGraphics();
    }

    /**
     * @param location lokasi penyimpanan image
     * @return true jika gambar ditemukan dan selain itu bernilai false
     */
    public boolean setImage(String location) {
        try {
            img = Image.createImage(location);
        } catch (IOException ex) {
            return false;
        }
        return true;
    }

    /**
     * @param display untuk menampilkan next display
     * @param next displayable yang akan ditampilkan selanjutnya setelah splash screen selesai
     */
    public void setNext(Display display, MainMenuAction next) {
        this.display = display;
        this.next = next;
        display.setCurrent(this);
    }

    public void draw(Graphics g) {
        if (img != null) {
            g.drawImage(img, 0, 0, 0);
        }
    }

    public void run() {
        int count = 0;
        while (true) {
            draw(graphics);
            if (count >= delayTime || stop) {
                break;
            }
            flushGraphics(0, 0, getWidth(), getHeight());
            count++;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
            }
        }
        next.action(0);
    }

    /**
     * Menjalankan splashscreen dan akan berhenti secara otomatis apabila mencapai waktu yang ditentukan.
     */
    public void start() {
        new Thread(this).start();
    }

    /**
     * Menghentikan splash screen
     */
    public void stop() {
        stop = true;
    }
}
